package com.zx.club.wx.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 缓存工具类
 *
 * @author zx
 * @date 2025-03-07 14:01
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String CACHE_KEY_SEPARATOR = ".";

    /**
     * 构建缓存key
     *
     * @param strObjs 需要构建缓存key的数组
     * @return 通过分隔符连接的字符串
     */
    public String buildKey(String... strObjs) {
        return String.join(CACHE_KEY_SEPARATOR, strObjs);
    }

    /**
     * 缓存key是否存在
     *
     * @param key 缓存key
     * @return 是否存在, true:存在, false:不存在
     */
    public boolean exist(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 设置缓存
     *
     * @param key   缓存key
     * @param value 缓存value
     */
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void setNx(String key, String value, Long time,TimeUnit timeout){
        redisTemplate.opsForValue().setIfAbsent(key, value, time,timeout);
    }

    public boolean del(String key){
        return Boolean.TRUE.equals(redisTemplate.delete(key));
    }

    public String get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public void expire(String key, Long time,TimeUnit timeout){
        redisTemplate.expire(key, time, timeout);
    }

    public Boolean zAdd(String key,String value,Long score){
        return redisTemplate.opsForZSet().add(key, value, score);
    }

    public Long countZset(String key){
        return redisTemplate.opsForZSet().size(key);
    }

    public Set<String> rangZset(String key,Long start,Long end){
        return redisTemplate.opsForZSet().range(key, start, end);
    }

    public Long removeZset(String key,String value){
        return redisTemplate.opsForZSet().remove(key, value);
    }

    public void removeZsetList(String key,Object values){
        redisTemplate.opsForZSet().remove(key, values);
    }

    public void removeZsetList(String key,Set<String> values){
        redisTemplate.opsForZSet().remove(key, values);
    }

    public Double score(String key,Object value){
        return redisTemplate.opsForZSet().score(key, value);
    }

    public Set<String> rangeByScore(String key,long start,long end){
        return redisTemplate.opsForZSet().rangeByScore(key, start, end);
    }

    public Object addScore(String key,Object value,double score){
        return redisTemplate.opsForZSet().incrementScore(key, value.toString() , score);
    }

    public Object rank(String key,Object obj){
        return redisTemplate.opsForZSet().rank(key, obj.toString());
    }
}
